package v1

import (
	"ginTea/model"
	"ginTea/utils/errmsg"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 添加商品
func AddGoods(c *gin.Context) {
	var code int
	var data model.Goods
	_ = c.ShouldBindJSON(&data)
	code = model.CreateGoods(&data)
	c.JSON(http.StatusOK, gin.H{
		"code":    code,
		"msg":     errmsg.GetErrMsg(code),
		"success": "success",
	})
}

// 删除商品
func DeleteGoods(c *gin.Context) {
	var code int
	id, _ := strconv.Atoi(c.Param("id"))
	code = model.DeleteGoods(id)
	if code == errmsg.ERROR_GOODS_NOT_EXIST {
		c.JSON(http.StatusOK, gin.H{
			"code":    code,
			"msg":     errmsg.GetErrMsg(code),
			"success": false,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  errmsg.GetErrMsg(code),
		})
	}
}

// 获取商品列表
func GetGoodsList(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	page, _ := strconv.Atoi(c.Query("page"))
	cid, _ := strconv.Atoi(c.Query("category_id"))
	keyword := c.Query("keyword")
	if pageSize == 0 {
		pageSize = 10
	}
	if page == 0 {
		page = 1
	}
	data := model.GetGoodsList(page, pageSize, keyword, cid)
	c.JSON(http.StatusOK, data)
}

// 获取某个分类下的所有商品
func GetGoodsByCategoryId(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	page, _ := strconv.Atoi(c.Query("page"))
	id, _ := strconv.Atoi(c.Query("id"))
	if pageSize == 0 {
		pageSize = -1
	}
	if page == 0 {
		page = -1
	}
	data := model.GetGoodsByCategoryId(page, pageSize, id)
	c.JSON(http.StatusOK, data)
}

// 获取商品详情
func GetGoodsInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	data, code := model.GetGoodsInfo(id)
	c.JSON(http.StatusOK, gin.H{
		"code":    code,
		"data":    data[0],
		"msg":     errmsg.GetErrMsg(code),
		"success": true,
	})
}

// 编辑商品
func UpdateGoods(c *gin.Context) {
	var code int
	var data model.Goods
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&data)
	code = model.UpdateGoods(id, &data)
	c.JSON(http.StatusOK, gin.H{
		"code":    code,
		"msg":     errmsg.GetErrMsg(code),
		"success": true,
	})
}
